<?php
use szktor\Http;
use szktor\Sms;
use think\Db;
use think\facade\Env;
use think\facade\Url;
use think\facade\Cache;
use think\facade\Request;
use app\common\model\Config as CfgModel;
use think\facade\Config as tpConfig;
use szktor\ClinicDict; //诊所门店公共字典

/**
 * 中药规格文字提取
 * 示例：1g/盒    数量 单位 / 库存单位
 */
if (!function_exists('_getZhongYaoSpecText')) {
    function _getZhongYaoSpecText($arr = []) {
    	return '';
    }
}
/**
 * 西药处方规格文字提取
 * 示例：1片*20片/盒    剂量 剂量单位 * 制剂量 制剂单位 / 库存单位
 */
if (!function_exists('_getXiYaoSpecText')) {
    function _getXiYaoSpecText($arr = []) {
    	$xy_jlunit_list = ClinicDict::getDrugsJiLiangUnitList(); //西药 - 剂量单位
        $xy_zjunit_list = ClinicDict::getDrugsZhiJiUnitList(); //西药 - 制剂单位
        $xy_kcunit_list = ClinicDict::getDrugsKuCunUnitList(); //西药 - 库存单位
    	return $arr['jl_num']._getDictNameTxt($arr['jl_unit'],$xy_jlunit_list)
    	.'*'.
    	$arr['zj_num']._getDictNameTxt($arr['zj_unit'],$xy_zjunit_list)
    	.'/'.
    	_getDictNameTxt($arr['kc_unit'],$xy_kcunit_list);
    }
}
/**
 * 手机号或银行卡号保留前四位和后四位，其余替换成*号
 */
if (!function_exists('_showCardStarNumber')) {
    function _showCardStarNumber($str = '', $startlen = 4, $endlen = 4) {
    	$repstr = "";
    	if(!$str) return $str;
	    if (strlen($str) < ($startlen + $endlen+1)) {
	        return $str;
	    }
	    $count = strlen($str) - $startlen - $endlen;
	    for ($i = 0; $i < $count; $i++) {
	        $repstr.="*";
	    }
	    return preg_replace('/(\d{' . $startlen . '})\d+(\d{' . $endlen . '})/', '${1}' . $repstr . '${2}', $str);
    }
}
/**
 * 获取字典中的 name
 */
if (!function_exists('_getDictNameTxt')) {
    function _getDictNameTxt($id = 0, $dictArr = [], $name='name', $idkey='id') {
       $txt = '';
       if(count($dictArr))
       {
			foreach ($dictArr as $k => $v) {
				if($v[$idkey] == $id)
				{
					$txt = $v[$name];
					break;
				}
			}
       }
       return $txt;
    }
}
/**
 * 单功能权限检测 , 比如按扭、连接等 , 根据用户已有权限
 * style="{:_checkRuleUrl('/index/store.kucun/to_excel',$admin['id'])}"
*/
if (!function_exists('_checkRuleUrl')) {
    function _checkRuleUrl($_url = '', $adminid = 0) {
    	$cacheName = md5('cms_index_adminrules_list_' . $adminid);
		$rulesArr = Cache::get($cacheName);
		$rulesArr = !$rulesArr ? [] : json_decode($rulesArr,true);
    	$falseStr = 'display:none;';
    	$trueStr = '';
        if(!$_url || count($rulesArr) <= 0) return $falseStr;
		$_url = strtolower($_url);
		$res = $falseStr;
		foreach($rulesArr as $key => $val)
		{
			if(strpos(trim(strtolower($val['url'])),';') > 0)
			{
				$_tmpArr = explode(';',trim(strtolower($val['url'])));
				if(in_array($_url,$_tmpArr))
				{
					$res = $trueStr;
					break;
				}
			}else{
				if(trim(strtolower($val['url'])) == strtolower($_url))
				{
					$res = $trueStr;
					break;
				}
			}
		}
		return $res;
	}
}
/**
 * 当前管理人员功能菜单权限匹配
 * return  false=有所有功能 / arr=仅部份功能
*/
if (!function_exists('_getCurrAdminRules')) {
    function _getCurrAdminRules($admin = [], $clinic = []) {
        if(!isset($admin['g_rules']) || !isset($clinic['g_rules'])) return ['-100']; //没有任何权限
        if($clinic['g_rules'] == '' || $clinic['g_rules'] == '*')
		{
			$clinicRules = false; //所有功能
		}else{
			$clinicRules = array_unique(explode(',',trim($clinic['g_rules'])));
			$clinicRules = count($clinicRules) > 0 ? $clinicRules : ['-1'];
		}
        if($admin['g_rules'] == '' || $admin['g_rules'] == '*')
		{
			//管理员--所有功能
			$adminRules = false; //所有功能
			if($clinicRules) $adminRules = $clinicRules; //但诊所被限制，则使用诊所的
		}else{
			//管理员--部分功能
			$adminRules = array_unique(explode(',',trim($admin['g_rules'])));
			$adminRules = count($adminRules) > 0 ? $adminRules : false;
			//所属门店有限制
			if($adminRules && $clinicRules)
			{
				$newRules = [];
				foreach($adminRules as $k => &$v)
				{
					$ruldId = (int)$v;
					if($ruldId <= 0) continue;
					if(!in_array($ruldId,$clinicRules)) continue;
					$newRules[] = $ruldId;
				}
				$adminRules = count($newRules) > 0 ? array_unique($newRules) : ['-2'];
			}else{
				if(!$adminRules) $adminRules = $clinicRules;
			}
		}
		unset($admin,$clinic,$clinicRules);
		return $adminRules;
    }
}
/**
 * 读取文件内容--将整个文件一下子读到一个字符串中
 * $filePath = 一个文件绝对路径，如：/home/www/123.txt
 * $readType = r (普通文件) rb(二进制文件)
 * @return 文件内容
 */
if (!function_exists('_readFileContent')) {
    function _readFileContent($filePath = '', $readType = 'r') {
		if (is_dir($filePath) || !file_exists($filePath)) return '';
		$handle = fopen($filePath,$readType);
		$content = '';
		while(false != ($a = fread($handle, 8080))){//返回false表示已经读取到文件末尾
		    $content .= $a;
		}
		fclose($handle);
		return $content;
    }
}
/**
 * 向手机号码发送短信
 * 签名不需要加  【】 符号
 * @return array
 */
if (!function_exists('_sendSMSMessage')) {
    function _sendSMSMessage($phone = '', $body = '', $sign = '') {
		$kxtCfg = CfgModel::getWebConfig('kxtsms');
		$smsObj = Sms::instance([
			'phone' => $phone, //当前手机号
			'body' => $body, //发送的内容
			'kxtid' => $kxtCfg['kxt_userid'], //凯信通用户ID
			'kxtuser' => $kxtCfg['kxt_account'], //凯信通用户名
			'kxtpwd' => $kxtCfg['kxt_password'], //凯信通密码
			'kxtsignname' => !$sign ? $kxtCfg['kxt_sign'] : trim($sign), //凯信通短信签名
		]);
		if(!$smsObj->checkPhone($phone))
		{
			return ['err' => 1, 'msg' => '手机号格式不正确'];
		}
		if(!$body)
		{
			return ['err' => 2, 'msg' => '要发送的短信内容不可为空'];
		}
        return $smsObj->send();
    }
}
//清理缓存
if (!function_exists('__clearnSystemCache'))
{
	function __clearnSystemCache() {
		$CACHE_PATH = Env::get('runtime_path').'cache'.DS;
		$TEMP_PATH = Env::get('runtime_path').'temp'.DS;
		$LOG_PATH = Env::get('runtime_path').'log'.DS;
		if (__deleteDirFile($CACHE_PATH) && __deleteDirFile($TEMP_PATH) && __deleteDirFile($LOG_PATH)) {
		    Cache::clear();
			return true;
		} else {
		    return false;
		}
	}
}
//清理缓存-删除目录函数
if (!function_exists('__deleteDirFile'))
{
	/**
	 * 循环删除目录和文件
	 * @param string $dir_name
	 * @return bool
	 */
	function __deleteDirFile($dir_name) {
	    $result = false;
	    if(is_dir($dir_name)){
	        if ($handle = opendir($dir_name)) {
	            while (false !== ($item = readdir($handle))) {
	                if ($item != '.' && $item != '..') {
	                    if (is_dir($dir_name . DS . $item)) {
	                        __deleteDirFile($dir_name . DS . $item);
	                    } else {
	                        unlink($dir_name . DS . $item);
	                    }
	                }
	            }
	            closedir($handle);
	            if (rmdir($dir_name)) {
	                $result = true;
	            }
	        }
	    }
	    return $result;
	}
}
/*
* 字节数Byte转换为KB、MB、GB、TB
*/
if(!function_exists("_formatFileSize")){
	function _formatFileSize($num = 0, $len = 3){
		$p = 0;
		$format='B';
		if($num>0 && $num<1024){
			$p = 0;
			return number_format($num).' '.$format;
		}
		if($num>=1024 && $num<pow(1024, 2)){
			$p = 1;
			$format = 'KB';
		}
		if ($num>=pow(1024, 2) && $num<pow(1024, 3)) {
			$p = 2;
			$format = 'MB';
		}
		if ($num>=pow(1024, 3) && $num<pow(1024, 4)) {
			$p = 3;
			$format = 'GB';
		}
		if ($num>=pow(1024, 4) && $num<pow(1024, 5)) {
			$p = 3;
			$format = 'TB';
		}
		$num /= pow(1024, $p);
		return number_format($num, $len).' '.strtolower($format);
	}
}
/*
* 运行日志  保存在  站点根目录下的 runtime/log/system_log_2018-01-21txt
*/
if(!function_exists("_writeSystemLog")){
    function _writeSystemLog($txt = '')
    {
        if(is_array($txt)) $txt = json_encode($txt,JSON_UNESCAPED_UNICODE);
        $str = "-----------------------------------" . date("Y-m-d H:i:s", time()) . "-----------------------------------\r\n";
        $str .= "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'] . "\r\n";
        $str .= $txt . "\r\n";
        $file = fopen(Env::get('root_path') . 'runtime/system_log_' . date("Y-m-d", time()) . '.txt', "a+");
        fwrite($file, $str);
        fclose($file);
    }
}
/*
*将一个价格格式化 保留两位小数
*/
if(!function_exists("_formatNumber")){
	function _formatNumber($money = 0)
	{
	  return substr(sprintf("%.3f",$money),0,-1);
	}
}
/**
 * 格式化金额
 * @param int $money
 * @param int $len
 * @param string $sign
 * @return string
 */
if(!function_exists("_formatMoney")){
	function _formatMoney($money, $len=2, $sign='￥')
	{
	    $negative = $money > 0 ? '' : ''; //-
	    $int_money = intval(abs($money));
	    $len = intval(abs($len));
	    $decimal = '';//小数
	    if ($len > 0) {
	        $decimal = '.'.substr(sprintf('%01.'.$len.'f', $money),-$len);
	    }
	    $format_money = '';
	    $tmp_money = strrev($int_money);
	    $strlen = strlen($tmp_money);
	    for ($i = 3; $i < $strlen; $i += 3)
	    {
	        $format_money .= substr($tmp_money,0,3).',';
	        $tmp_money = substr($tmp_money,3);
	    }
	    $format_money .= $tmp_money;
	    $format_money = strrev($format_money);
	    return $sign.$negative.$format_money.$decimal;
	}
}
/*
* 性别判断
* 性别，1.男2.女,0未知
*/
if(!function_exists("_getSexTxt")){
    function _getSexTxt($sex = 0)
	{
		if(intval($sex) <= 0) return '未知';
		if($sex == '1') return '男';
		return '女';
	}
}